package com.onenine.app.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;

import com.onenine.app.R;
import com.onenine.base.base.BaseActivity;
import com.onenine.base.utils.Toasty;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 头像上传
 */
public abstract class HeadPicUploadActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks {

    private final String[] mPermissions = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private final int RC_AVATAR = 0x0001;

    /**
     * 加载权限相册
     */
    protected void launchPermissionAlbum() {
        if (EasyPermissions.hasPermissions(this, mPermissions)) {
            launchMatisseAlbum();
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.permission_camera_hint)
                    , RC_AVATAR, mPermissions);
        }
    }

    /**
     * 拉起相册
     */
    private void launchMatisseAlbum() {
        Matisse.from(this)
                .choose(MimeType.ofImage())//只显示照片
                .capture(true)
                .showSingleMediaType(true)//只显示一种媒体类型，此处只会显示图片，过滤了视频
                .captureStrategy(new CaptureStrategy(true, getPackageName() + ".fileprovider"))
                .countable(false)//有序选择图片
                .maxSelectable(1)//最大选择数量为9
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//图像选择和预览活动所需的方向。
                .thumbnailScale(0.85f)//缩放比例
                .theme(R.style.Matisse_Light)//主题
                .imageEngine(new GlideEngine())//加载方式
                .forResult(RC_AVATAR);//请求码
    }

    /**
     * 压缩图片在100kb左右
     *
     * @param fileStr
     */
    private void compressImages(final String fileStr) {
        Luban.with(this)
                .load(fileStr).ignoreBy(100)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        showHeadPic(file.getAbsolutePath());
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == RC_AVATAR) {
                List<String> pathList = Matisse.obtainPathResult(data);
                if (pathList != null && !pathList.isEmpty()) {
                    compressImages(pathList.get(0));
                }
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == RC_AVATAR && perms.size() == mPermissions.length) {
            launchMatisseAlbum();
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(getString(R.string.permission_apply))
                    .setRationale(getString(R.string.permission_refuse_always_hint)).build().show();
        } else if (requestCode == RC_AVATAR) {
            Toasty.showNormal(R.string.permission_camera_hint);
        }
    }

    /**
     * 显示上传dialog
     */
    protected void showProgressOnMainThread(@StringRes final int resId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                showLoading(resId);
            }
        });
    }

    /**
     * 取消上传dilaog
     *
     * @param resId
     */
    protected void dismissProgressOnMainThread(@StringRes final int resId) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dismissLoading();
                Toasty.showNormal(resId);
            }
        });
    }

    /**
     * 显示头像
     *
     * @param absolutePath
     */
    protected abstract void showHeadPic(String absolutePath);

}
